<template>
  <ul
    ref="list"
    class="flex"
    :class="{
      'flex-row': !reverse && direction === 'col' && direction === 'column',
      'flex-row-reverse':
        reverse && direction !== 'col' && direction !== 'column',
      'flex-col': !reverse && (direction === 'col' || direction === 'column'),
      'flex-col-reverse':
        reverse && (direction === 'col' || direction === 'column'),
    }"
  >
    <slot></slot>
  </ul>
</template>

<script>
export default {
  mounted() {
    let doUpdate = true;
    const doUpdateInterval = 1000 / 60;
    /** @type { HTMLUListElement } */
    const listElement = this.$refs.list;
    new ResizeObserver(() => {
      if (doUpdate) {
        this.updateItemsWidth();
        doUpdate = false;
        setTimeout(() => {
          doUpdate = true;
        }, doUpdateInterval);
      }
    }).observe(listElement);
  },
  updated() {
    this.updateItemsWidth();
  },

  props: {
    direction: {
      type: String,
      default: "row",
    },
    reverse: {
      type: Boolean,
      default: false,
    },
  },

  methods: {
    updateItemsWidth() {
      // console.log("update items width");
      let maxWidth = 0;
      /** @type { HTMLUListElement } */
      const listElement = this.$refs.list;
      if (!listElement || !listElement.children) {
        return;
      }
      for (const li of listElement.children) {
        li.style.width = "";
        const lw = li.clientWidth;
        if (lw > maxWidth) {
          maxWidth = lw;
        }
      }
      for (const li of listElement.children) {
        li.style.width = maxWidth + "px";
      }
    },
  },
};
</script>
